//
//  HomeworkCalendarViewController.m
//  parent
//
//  Created by IreWesT on 15/5/28.
//  Copyright (c) 2015年 ci123. All rights reserved.
//

#import "HomeworkCalendarViewController.h"
#import "CalendarView.h"
#import "DayModel.h"
#import "NSDate+convenience.h"

#define DaySeconds 86400

@interface HomeworkCalendarViewController ()<
    CalendarViewDelegate,
    UITableViewDataSource,
    UITableViewDelegate
>

@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) UIView *topView;
@property (nonatomic, retain) UILabel *monthTitle;
@property (nonatomic, retain) CalendarView *calendarView;

@property (nonatomic, retain) NSMutableDictionary *cacheData;
@property (nonatomic, retain) NSMutableDictionary *cacheHomeworks;
@property (nonatomic, retain) NSArray *homeworkList;
@property (nonatomic, copy) NSString *avatarPrefix;

@property (nonatomic,retain)NSDate *currentMonth;
@property (nonatomic,assign)NSInteger todayStamp;
@property (nonatomic,assign)NSInteger selectedDateStamp;
@property (nonatomic,retain)DayModel *selectedModel;
@property (nonatomic,retain)DayModel *todayModel;

@end

@implementation HomeworkCalendarViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"作业历史";
    self.todayStamp = [UIUtils todayStamp];
    self.currentMonth = [NSDate currentMonth];
    self.selectedDateStamp = self.todayStamp;
    if ([self respondsToSelector:@selector(edgesForExtendedLayout)])
        self.edgesForExtendedLayout = UIRectEdgeNone;
    [self _initView];
    [self _initData];
}

- (void)viewWillAppear:(BOOL)animated {

    [super viewWillAppear:animated];
    
    [_calendarView showViews];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - View

- (void)_initView {

    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, APP_SCREEN_WIDTH, APP_SCREEN_HEIGHT - self.navHeight) style:UITableViewStyleGrouped];
    _tableView.backgroundColor = [UIColor whiteColor];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    
    CGFloat inch = [UIUtils applicationSreenInch];
    CGFloat cellWidth = 40.0f;
    if (inch == 5.5 || inch == 4.7) {
        cellWidth = 48.0f;
    }
    CGFloat slideViewHeight = 42.0f;
    CGFloat calendarViewHeight = 42.0f + cellWidth * 6;
    CGFloat gap = 31.0f;
    
    _topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, _tableView.width, slideViewHeight + calendarViewHeight + gap)];
    _topView.backgroundColor = UIColorMake(240, 240, 240);
    _tableView.tableHeaderView = _topView;
    
    UIView *slideView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, _topView.width, slideViewHeight)];
    slideView.backgroundColor = [UIColor whiteColor];
    [_topView addSubview:slideView];
    
    _monthTitle = [[UILabel alloc] initWithFrame:CGRectMake((slideView.width - 120) / 2, 0, 120, slideView.height)];
    _monthTitle.backgroundColor = [UIColor clearColor];
    _monthTitle.textColor = UIColorMake(118, 118, 118);
    _monthTitle.font = [UIFont systemFontOfSize:16.0f];
    _monthTitle.textAlignment = NSTextAlignmentCenter;
    [slideView addSubview:_monthTitle];
    
    UIButton *leftButton = [[UIButton alloc] initWithFrame:CGRectMake(3, 0, 42, slideViewHeight)];
    leftButton.backgroundColor = [UIColor clearColor];
    leftButton.showsTouchWhenHighlighted = YES;
    [leftButton setImage:[UIImage imageNamed:@"calendarview_btn_left"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(slideLastMonth:) forControlEvents:UIControlEventTouchUpInside];
    [slideView addSubview:leftButton];
    
    UIButton *rightButton = [[UIButton alloc] initWithFrame:CGRectMake(slideView.width - 3 - 42, 0, 42, slideViewHeight)];
    rightButton.backgroundColor = [UIColor clearColor];
    rightButton.showsTouchWhenHighlighted = YES;
    [rightButton setImage:[UIImage imageNamed:@"calendarview_btn_right"] forState:UIControlStateNormal];
    [rightButton addTarget:self action:@selector(slideNextMonth:) forControlEvents:UIControlEventTouchUpInside];
    [slideView addSubview:rightButton];
    
    _calendarView = [[CalendarView alloc] initWithFrame:CGRectMake(19.5, slideViewHeight, APP_SCREEN_WIDTH - 19.5 * 2, calendarViewHeight)];
    _calendarView.delegate = self;
    [_topView addSubview:_calendarView];
    
    [self updateTitleDate];
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 20 , 44, 44)];
    button.showsTouchWhenHighlighted = YES;
    button.backgroundColor = [UIColor clearColor];
    button.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 30);
    [button setImage:[UIImage imageNamed:@"nav_btn_back"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(backPage:) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc]
                                   initWithTitle:@""
                                   style:UIBarButtonItemStylePlain
                                   target:nil
                                   action:nil];
    self.navigationItem.backBarButtonItem=backButton;
}
-(void)backPage:(id)button{
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)updateTitleDate
{
    NSString *str = [UIUtils stringFromFomate:_currentMonth formate:@"yyyy年MM月"];
    [_monthTitle setText:str];
}

- (void)updateData {

    if (_calendarView) {
        _selectedModel = [_calendarView reloadDataWithMonth:_currentMonth];
        [self dayClick:_selectedModel];
    }
}

- (void)updateHomework:(NSDictionary *)dic {
    
    if (!dic || dic.count <= 0) {
        _homeworkList = [NSArray new];
    }else {
        _avatarPrefix = [NSString stringWithFormat:@"%@", dic[@"avatar_header"]];
        _homeworkList = dic[@"homeworks"] ? : [NSArray new];
    }
    [_tableView reloadData];
}

- (void)_initData {

    [self apiGetAllCalendarHomeworks:_currentMonth];
}

- (void)dealData:(NSDictionary *)dic withYear:(NSInteger)year withMonth:(NSInteger)month{

    if (!dic || dic.count <= 0) {
        return;
    }
    
    if (!_cacheData) {
        _cacheData = [[NSMutableDictionary alloc] init];
    }
    
    NSString *key;
    if (dic[@"days"] && dic[@"year"] && dic[@"month"]) {
        key = [NSString stringWithFormat:@"%@-%02ld", dic[@"year"], (long)[dic[@"month"] integerValue]];
    }else {
        key = [NSString stringWithFormat:@"%ld-%02ld", (long)year, (long)month];
    }
    [_cacheData setObject:dic forKey:key];
}

- (void)dealHomework:(NSDictionary *)dic withStamp:(NSInteger)stamp{

    if (!dic) {
        return;
    }
    
    if (!_cacheHomeworks) {
        _cacheHomeworks = [[NSMutableDictionary alloc] init];
    }
    
    NSString *key = [NSString stringWithFormat:@"%ld", (long)stamp];
    [_cacheHomeworks setObject:dic forKey:key];
}

- (NSString *)getKeyByDate:(NSDate *)date {

    return [NSString stringWithFormat:@"%ld-%02ld", date.year, date.month];
}

#pragma mark - Networking

-(BOOL)apiGetAllCalendarHomeworks:(NSDate *)month {
    
    NSUInteger classid = [[UserDao getInstance]getCurrentBaby].classid;
    if(classid <= 0){
        debugLog(@"未加入班级");
        return NO;
    }
    
    NSString* uid = [NSString stringWithFormat:@"%ld",[[UserDao getInstance] getUserId]];
    NSString* utype = @"1";
    NSInteger monthYear = [month year];
    NSInteger monthMonth = [month month];
    
    NSDictionary *temp_dict = @{@"uid":uid,
                                @"utype":utype,
                                @"token":[[UserDao getInstance]getAccessToken],
                                @"classid":@(classid),
                                @"year":@(monthYear),
                                @"month":[NSString stringWithFormat:@"%02ld", (long)monthMonth]};
    
    NSString *dataString = [JsonUtil convertDictionaryToJson:temp_dict];
    
    NSString *msg = @"USER_GET_HOMEWORK_DATES";
    
    [[NetWorkManager getInstanse] requestURLAsynMessage:msg data:dataString FinishBlock:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

        if (connectionError) { //连接失败
            NSLog(@"Http Error: %@   %ld", connectionError.localizedDescription,(long)connectionError.code);
            NSString *error_content = [NSString stringWithFormat:@"连接错误:%ld",(long)connectionError.code];
            PopUIManager *popUIMgr = [PopUIManager getInstanse];
            [popUIMgr popAlertView:nil title:@"提示" message:error_content cancelButtonTitle:@"确定"];
        }else{//连接成功，判断是否有数据返回
            if (data) {
                NSDictionary *dict = [JsonUtil convertDataToDictionary:data];
                if ([[dict objectForKey:@"retCode"] integerValue] == 1) {
                    [self dealData:dict withYear:monthYear withMonth:monthMonth];
                    if (dict[@"days"]) {
                        if ((_currentMonth.year == [dict[@"year"] integerValue]) && (_currentMonth.month == [dict[@"month"] integerValue])) {
                            [self updateData];
                        }
                    }
                }else if ([[dict objectForKey:@"retCode"] integerValue] == 10020) {
                }else{
                    PopUIManager *popUIMgr = [PopUIManager getInstanse];
                    [popUIMgr popAlertView:nil title:@"提示" message:@"数据解析错误" cancelButtonTitle:@"确定"];
                }
            }else{
                PopUIManager *popUIMgr = [PopUIManager getInstanse];
                [popUIMgr popAlertView:nil title:@"提示" message:@"服务器没有返回数据" cancelButtonTitle:@"确定"];
            }
        }
    }];
    return YES;
}

-(BOOL)apiGetHomeworkByStamp:(NSInteger)stamp {
    
    NSUInteger classid = [[UserDao getInstance]getCurrentBaby].classid;
    if(classid <= 0){
        debugLog(@"未加入班级");
        return NO;
    }
    
    NSString* uid = [NSString stringWithFormat:@"%ld",[[UserDao getInstance] getUserId]];
    NSString* utype = @"1";
    
    NSDictionary *temp_dict = @{@"uid":uid,
                                @"utype":utype,
                                @"token":[[UserDao getInstance]getAccessToken],
                                @"classid":@(classid),
                                @"date":[UIUtils fullDateStringFromStamp:stamp]};
    
    NSString *dataString = [JsonUtil convertDictionaryToJson:temp_dict];
    
    NSString *msg = @"USER_GET_HOMEWORK_BY_DATE";
    
    [[NetWorkManager getInstanse] requestURLAsynMessage:msg data:dataString FinishBlock:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        
        if (connectionError) { //连接失败
            NSLog(@"Http Error: %@   %ld", connectionError.localizedDescription,(long)connectionError.code);
            NSString *error_content = [NSString stringWithFormat:@"连接错误:%ld",(long)connectionError.code];
            PopUIManager *popUIMgr = [PopUIManager getInstanse];
            [popUIMgr popAlertView:nil title:@"提示" message:error_content cancelButtonTitle:@"确定"];
        }else{//连接成功，判断是否有数据返回
            if (data) {
                NSDictionary *dict = [JsonUtil convertDataToDictionary:data];
                if ([[dict objectForKey:@"retCode"] integerValue] == 1) {
                    [self dealHomework:dict withStamp:stamp];
                    [self updateHomework:dict];
                }else if ([[dict objectForKey:@"retCode"] integerValue] == 10020){
                    
                    [self dealHomework:[NSDictionary new] withStamp:stamp];
                    [self updateHomework:dict];
                }else{
                    PopUIManager *popUIMgr = [PopUIManager getInstanse];
                    [popUIMgr popAlertView:nil title:@"提示" message:@"数据解析错误" cancelButtonTitle:@"确定"];
                }
            }else{
                PopUIManager *popUIMgr = [PopUIManager getInstanse];
                [popUIMgr popAlertView:nil title:@"提示" message:@"服务器没有返回数据" cancelButtonTitle:@"确定"];
            }
        }
    }];
    return YES;
}

#pragma mark - CalendarViewDelegate

- (NSArray *)getDataWithMonth:(NSDate *)month {
    
    NSUInteger numDays = [month numDaysInMonth];
    NSInteger monthYear = [month year];
    NSInteger monthMonth = [month month];
    NSInteger firstStamp = [UIUtils stampFromDateString:[NSString stringWithFormat:@"%ld-%02ld-01", (long)monthYear, (long)monthMonth]];
    NSInteger lastStamp = firstStamp + (numDays - 1) * DaySeconds;
    
    NSMutableArray *days = [[NSMutableArray alloc] initWithCapacity:numDays];
    
    NSString *key = [self getKeyByDate:month];
    NSDictionary *homeworkDays = [_cacheData valueForKey:key] ? : [NSDictionary new];
    NSMutableArray *tempArr = [[NSMutableArray alloc] init];
    for (NSString *day in homeworkDays[@"days"]) {
        NSInteger stamp = [UIUtils stampFromDateString:[NSString stringWithFormat:@"%ld-%02ld-%@", (long)monthYear, (long)monthMonth, day]];
        [tempArr addObject:[NSString stringWithFormat:@"%ld", (long)stamp]];
    }
    
    BOOL hasHomework;
    for (NSInteger stamp = firstStamp; stamp <= lastStamp; stamp += DaySeconds) {
        NSString *stampStr = [NSString stringWithFormat:@"%ld", (long)stamp];
        
        hasHomework = NO;
        if ([tempArr containsObject:stampStr]) {
            hasHomework = YES;
        }
        
        DayModel *model = [[DayModel alloc] initWithStamp:stamp hasHomework:hasHomework];
        [days addObject:model];
        
        if (stamp == _selectedDateStamp) {
            _selectedModel = model;
        }
        
        if (stamp == _todayStamp) {
            _todayModel = model;
        }
    }
    
    return days;
}

- (void)showViewFinished {
    
}

- (void)dayClick:(DayModel *)dayModel {
    
    _selectedModel = dayModel;
    _selectedDateStamp = _selectedModel.stamp;
    if (_selectedDateStamp == _todayStamp) {
        _todayModel = _selectedModel;
    }
    
    NSString *key = [NSString stringWithFormat:@"%ld", (long)_selectedDateStamp];
    NSDictionary *dic = [_cacheHomeworks valueForKey:key];
    if (dic) {
        [self updateHomework:dic];
    }else {
        [self apiGetHomeworkByStamp:_selectedDateStamp];
    }
}

- (void)moveMonth:(NSDate *)month withOffset:(NSInteger)offset
{
    _currentMonth = month;
    [self updateTitleDate];
    
    NSString *key = [self getKeyByDate:_currentMonth];
    if (![_cacheData valueForKey:key]) {
        [self apiGetAllCalendarHomeworks:_currentMonth];
    }
}


#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    return CGFLOAT_MIN;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *CellIdentifier = @"CellStyleHomework";
    
    UITableViewCell *cell = [_tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if(cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.backgroundColor = [UIColor whiteColor];
        
        UIImageView *head = [[UIImageView alloc] initWithFrame:CGRectMake(25, 23, 34, 34)];
        head.backgroundColor = [UIColor clearColor];
        head.layer.cornerRadius = 17.0f;
        head.layer.masksToBounds = YES;
        head.tag = 1001;
        [cell.contentView addSubview:head];
        
        UILabel *content = [[UILabel alloc] initWithFrame:CGRectMake(head.right + 21, 18, APP_SCREEN_WIDTH - head.right - 21 - 25, 42)];
        content.backgroundColor = [UIColor clearColor];
        content.textColor = UIColorMake(90, 90, 90);
        content.font = [UIFont systemFontOfSize:16.0f];
        content.numberOfLines = 0;
        content.lineBreakMode = NSLineBreakByTruncatingTail;
        content.tag = 1002;
        [cell.contentView addSubview:content];
    }
    
    UIImageView *head = (UIImageView *)[cell.contentView viewWithTag:1001];
    CGFloat originX = 0;
    if (indexPath.row == 0) {
        head.hidden = NO;
        originX = 18;
    }else {
        head.hidden = YES;
        head.image = nil;
    }
    UILabel *content = (UILabel *)[cell.contentView viewWithTag:1002];
    content.top = originX;
    NSString *headString = [NSString stringWithFormat:@"%@%@", _avatarPrefix, _homeworkList[indexPath.section][@"avatar"]];
    [head sd_setImageWithURL:[NSURL URLWithString:headString]];
    content.text = [NSString stringWithFormat:@"%@", _homeworkList[indexPath.section][@"hmwks"][indexPath.row]];
    
    return cell;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _homeworkList.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [_homeworkList[section][@"hmwks"] count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == 0) {
        return 78.0f;
    }
    return 42.0f;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

#pragma mark - Action

- (void)returnToday:(UIButton *)button
{
    [_calendarView returnTodayMonth];
    _currentMonth = [NSDate currentMonth];
    [self updateTitleDate];
}

- (void)slideLastMonth:(UIButton *)button {
    
    [_calendarView turnLastMonth];
}

- (void)slideNextMonth:(UIButton *)button {
    
    [_calendarView turnNextMonth];
}

@end
